//
//  AddPhoneViewController.m
//  Mahjong
//
//  Created by KING on 16/9/18.
//  Copyright © 2016年 swift. All rights reserved.
//

#import "AddPhoneViewController.h"
#import "ZYQAssetPickerController.h"
#import "HCSStarRatingView.h"
#import "Header.h"
#define ScreenHeight    [[UIScreen mainScreen] bounds].size.height
#define ScreenWidth     [[UIScreen mainScreen] bounds].size.width


@interface AddPhoneViewController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
{
    UIView               *_editv;
    UITextView           *_textView;
    UILabel              *_placeholderLabel;
    UIButton             *_addPic;
    NSMutableArray       *_imageArray;
    UILabel              *starLabel;
    HCSStarRatingView    *starRatingView;
    NSString *starString;
}


@end

@implementation AddPhoneViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1];
    _imageArray = [NSMutableArray array];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, ScreenWidth, 30)];
    label.backgroundColor = [UIColor whiteColor];
    label.text = @"您的评价,让我们做的更好";
    [label setFont:[UIFont systemFontOfSize:14]];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor lightGrayColor];
    [self.view addSubview:label];
    
    // 评论 + 照片
    _editv = [[UIView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, 0)];
    _editv.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_editv];
    
    // 评论 UITextView
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 15, CGRectGetWidth(_editv.frame)-15*2, 70)];
    _textView.backgroundColor = [UIColor whiteColor];
    _textView.delegate = self;
    [_editv addSubview:_textView];
    
    // 提示字
    _placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel.frame =CGRectMake(5, 6, CGRectGetWidth(_editv.frame)-15*4, 20);
    _placeholderLabel.text = @"意见留言";
    _placeholderLabel.textColor = [UIColor colorWithWhite:0.4 alpha:0.6];
    _placeholderLabel.font = [UIFont systemFontOfSize:12.0];
    _placeholderLabel.enabled = NO; // lable必须设置为不可用
    _placeholderLabel.backgroundColor = [UIColor clearColor];
    [_textView addSubview:_placeholderLabel];
    
    // + pic
    _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
    _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70, 70);
    [_addPic setImage:[UIImage imageNamed:@"service_but_addpicture@2x"] forState:UIControlStateNormal];
    [_addPic addTarget:self action:@selector(addPicEvent) forControlEvents:UIControlEventTouchUpInside];
    [_editv addSubview:_addPic];
    
    starLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _editv.frame.size.height+95+10, ScreenWidth, 20)];
    starLabel.textColor = [UIColor lightGrayColor];
    starLabel.text = @"门店评分";
    [starLabel setFont:[UIFont systemFontOfSize:15]];
    [_editv addSubview:starLabel];
    
    starRatingView = [[HCSStarRatingView alloc] initWithFrame:CGRectMake(10, _editv.frame.size.height+95+10+30, 280, 35)];
    starRatingView.maximumValue = 5;
    starRatingView.minimumValue = 0;
    starRatingView.value = 4.5f;//初始星级位置
    starRatingView.allowsHalfStars = YES;//是否允许半星级
    starRatingView.spacing = 1;
    starRatingView.tintColor = [UIColor redColor];
    starRatingView.tintColor = [UIColor colorWithRed:253/255.0 green:135/255.0 blue:9/255.0 alpha:1];
    [starRatingView addTarget:self action:@selector(didChangeValue:) forControlEvents:UIControlEventValueChanged];
    [_editv addSubview:starRatingView];
    
    
    
    _editv.frame = CGRectMake(0, 95, ScreenWidth, CGRectGetMaxY(_addPic.frame)+20+150);
    starLabel.frame = CGRectMake(20, _editv.frame.size.height-105, ScreenWidth, 20);
    starRatingView.frame = CGRectMake(20, _editv.frame.size.height-75, 200, 25);
    
    self.navigationItem.title = @"匿名评价";
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_but_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction)];
    backItem.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = backItem;
    
}

- (void)backAction{
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=Insertcomment&comment=%@&star=%@&giftid=%@&giftdetailid=%@&userid=%@",_textView.text,starString,@"7",@"2",USERID] success:^(id result) {
        
        NSLog(@"%@%@",result,[result[0] objectForKey:@"describe"]);
        for (int i = 0; i<_imageArray.count; i++) {
        NSData *fileData = UIImageJPEGRepresentation(_imageArray[i ], 1.0);
        NSString *encodedString = [fileData base64Encoding];
        NSDictionary *dic = @{@"commentid":[result[0] objectForKey:@"commentid"],@"Code":encodedString,@"Userid":USERID};
        [AppTools postData:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=InsertcommentImage&"] from:^(id data) {
            
            
        } dic:dic success:^(id result) {
            NSLog(@"%@",result);
            
        } error:^(NSError *error) {
//            NSLog(@"%@",error);
            
        }];
            
            
        }
        
        
    } error:^(NSError *error) {
        
        
    }];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didChangeValue:(HCSStarRatingView *)sender
{
//    starLabel.text = [NSString stringWithFormat:@"%.1f 星级",sender.value];
    starString = [NSString stringWithFormat:@"%.1f",sender.value];
    NSLog(@"Changed rating to %.1f", sender.value);
}
#pragma mark - UIbutton event

- (void)addPicEvent
{
    if (_imageArray.count >= 6) {
        NSLog(@"最多只能上传9张图片");
    } else {
        [self selectPictures];
    }
}

// 本地相册选择多张照片
- (void)selectPictures
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 6-_imageArray.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
                              {
                                  if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
                                  {
                                      NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                                      
                                      return duration >= 5;
                                  } else {
                                      return YES;
                                  }
                              }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

// 9宫格图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _editv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = ScreenWidth/5;
    CGFloat widthSpace = (ScreenWidth - 15*4 - (ScreenWidth/5.5)*4) / 3.0;
    CGFloat heightSpace = 10;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 6 ? (count = 6) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(15+(width+widthSpace)*(i%4), (i/4)*(width+heightSpace) + CGRectGetMaxY(_textView.frame)+15, width, width)];
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_editv addSubview:imgv];
        
//        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
//        delete.frame = CGRectMake(width-16, 0, 16, 16);
////        delete.backgroundColor = [UIColor greenColor];
//        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
//        delete.tag = 10+i;
//        [delete setImage:[UIImage imageNamed:@"else_but_closepop@2x"] forState:UIControlStateNormal];
//        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(15, CGRectGetMaxY(imgv.frame) + heightSpace, 70, 70);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame), 70, 70);
            }
            
            _editv.frame = CGRectMake(0, 95, ScreenWidth, CGRectGetMaxY(_addPic.frame)+20+150);
            starLabel.frame = CGRectMake(20, _editv.frame.size.height-105, ScreenWidth, 20);
            starRatingView.frame = CGRectMake(20, _editv.frame.size.height-75, 200, 25);
        }
    }
}

// 删除照片
//- (void)deleteEvent:(UIButton *)sender
//{
//    UIButton *btn = (UIButton *)sender;
//    [_imageArray removeObjectAtIndex:btn.tag-10];
//    
//    [self nineGrid];
//    
//    if (_imageArray.count == 0)
//    {
//        _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70, 70);
//        _editv.frame = CGRectMake(0, 95, ScreenWidth, CGRectGetMaxY(_addPic.frame)+20+50);
//    }
//}

#pragma mark - ZYQAssetPickerController Delegate

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ALAsset *asset = assets[i];
                           UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                           [_imageArray addObject:tempImg];
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self nineGrid];
                           });
                       }
                   });
}

#pragma makr - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0) {
        _placeholderLabel.text = @"意见留言";
    } else {
        _placeholderLabel.text = @"";
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
